package com.huanletao.tran;

import com.huanletao.spring.multdatasource.CustTransactional;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

/**
 * <p>
 *     测试多数据源，事务处理；
 * </p>
 * package: com.huanletao.tran
 * description:
 * className: UserService3
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/8/23 9:42
 * since: 1.0.0
 */
@Component
public class UserService3 {

    @Resource(name = "jdbcTemplateMaster")
    JdbcTemplate jdbcTemplateMaster;

    @Resource(name = "jdbcTemplateSlave")
    JdbcTemplate jdbcTemplateSlave;
    @Resource
    StudentService studentService;
    @Resource
    PlatformTransactionManager transactionManagerSlave;
    @Resource
    PlatformTransactionManager transactionManagerMaster;

    /**
     * 1. 第一种情况，两个操作都在一个service方法
     *
     */
    @CustTransactional({"transactionManagerMaster","transactionManagerSlave"})
    public void transfer(){
        jdbcTemplateMaster.update("insert into user(username,mony) values(?,?)","刘备121",12);
        jdbcTemplateSlave.update("insert into student(username,password) values(?,?)","刘备111","123456");
        int i=1/0;
    }

    /**
     * 测试两个事务service；
     */
    public void saveTwoTables(){
        TransactionStatus status = transactionManagerMaster.getTransaction(new DefaultTransactionDefinition());
        TransactionStatus status1 = transactionManagerSlave.getTransaction(new DefaultTransactionDefinition());

        try {
            jdbcTemplateMaster.update("insert into user(username,mony) values(?,?)","刘备",12);
            studentService.insertStdents();
            transactionManagerSlave.commit(status1);
            transactionManagerMaster.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            transactionManagerMaster.rollback(status);
            transactionManagerSlave.rollback(status1);
        }
    }
}
